package com.snakegame.util;

import com.snakegame.config.Map;
import com.snakegame.entity.Food;
import com.snakegame.entity.Point;
// 删除未使用的导入语句
// import com.snakegame.core.GameManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 食物生成器，负责在地图上生成食物
 */
public class FoodGenerator {
    // 将 random 字段设为 final
    private static final Random random = new Random();

    public static Food generateFood(Map map, List<com.snakegame.entity.Snake> snakes) {
        List<Point> availablePositions = new ArrayList<>();
        
        // 收集所有可用位置
        for (int x = 0; x < map.getWidth(); x++) {
            for (int y = 0; y < map.getHeight(); y++) {
                // 使用 com.snakegame.entity.Point 类型
                com.snakegame.entity.Point entityPoint = new com.snakegame.entity.Point(x, y);
                // 转换为 java.awt.Point 类型
                java.awt.Point awtPoint = new java.awt.Point(entityPoint.x, entityPoint.y);

                // 检查是否是墙
                if (map.isWall(awtPoint)) {
                    continue;
                }
                
                // 检查是否与蛇身重叠
                boolean overlapsSnake = false;
                for (com.snakegame.entity.Snake snake : snakes) {
                    if (snake.getBody().contains(entityPoint)) {
                        overlapsSnake = true;
                        break;
                    }
                }
                
                if (!overlapsSnake) {
                    availablePositions.add(entityPoint);
                }
            }
        }
        
        // 随机选择一个可用位置
        if (!availablePositions.isEmpty()) {
            int index = random.nextInt(availablePositions.size());
            return new Food(availablePositions.get(index));
        }
        
        com.snakegame.entity.Point centerPoint = new com.snakegame.entity.Point(map.getWidth() / 2, map.getHeight() / 2);
        return new Food(centerPoint);
        // 如果没有可用位置，返回地图中心位置
    }
}    